from django import forms
#from django.template import Context, Template
#from django.template.loader import get_template
from django.utils.safestring import mark_safe

from pypsqueak.artifact.models import Artifact

class AjaxFileUploadWidget(forms.FileInput):
	"""
	Uses js lib for ajax uploads
	See http://valums.com/ajax-upload/ for description and code.
	Depends on form named of MainForm.
	"""
	class Media:
		js = (
			"/files/lib/jquery/js/jquery-1.3.2.min.js",
			"/files/lib/jquery.form/jquery.form.js",
			);

	def set_url(self, url):
		""" Calling programs need to say where the file should be uploaded to """
		self.url = url

	def set_ajax_target(self, div_name):
		""" Set the ajax div that should be used as a target for the postback. """
		self.ajax_target = div_name

	def render(self, name, value, attrs=None):
		output = super( AjaxFileUploadWidget, self ).render(name, value, attrs)
		return  mark_safe(
u'''
<script type="text/javascript">

	function UploadFile() {
		// Need to manually set the ?xhr variable so I can detect this is an AJAX
		//	call in the view.  Because this lib uses an iframe to post the file,
		//	the jQuery library doesn't set the standard headers.
		// Assumes calling view will wrap the resulting html text in a div titled 'wrapper'
		var options = {

			url:		'%(page_url)s?xhr=true',
			type:		'POST',
			dataType:	'xml',
			success:	function(responseText, statusText) {
							$('#%(name)s_working').hide();
							$('#id_%(name)s').val('');
							$('#%(target)s').prepend(responseText.getElementById('wrapper').firstChild);
						}
		};

		$('#%(name)s_working').show();
		$('#MainForm').ajaxSubmit(options);
	}

</script>

%(output)s
<button type="button" onclick="javascript:UploadFile();" id="%(name)s_submit">Upload</button>

<span id="%(name)s_working" style="display:none;" >
	<img src="/files/images/working.gif"> uploading...
</span>

''' % ({
	'output': output,
	'name': name,
	'target':self.ajax_target,
	'page_url':self.url
		})
)


